import { computed, reactive, inject } from 'vue'
import { useBuildAttrsKeys, AConfigProviderTypes } from '@/components'

const usePagination = (props: Record<string, any>) => {
  // 如果 没有 分页
  if (!props.paginationConfig) {
    return {
      paginationData: computed(() => props.tableData),
      paramsConfigs: {
        pageNo: undefined,
        pageSize: undefined
      },
      indexStart: computed(() => 0)
    }
  }

  //   如果有分页
  const attrs = inject<AConfigProviderTypes>(useBuildAttrsKeys)
  const { CETable } = attrs as any
  const { transformParams } = CETable
  const config = transformParams(props.paramsConfig)

  const paramsConfigs = reactive(config)

  const indexStart = computed(
    () => (paramsConfigs.pageNo - 1) * paramsConfigs.pageSize
  )

  const paginationData = computed(() => {
    const start = indexStart.value
    const end = start + paramsConfigs.pageSize
    if (props.tableData.length) return props.tableData.slice(start, end)
    return []
  })

  return {
    paginationData,
    paramsConfigs,
    indexStart
  }
}

export { usePagination }
